package com.byb.server.web.rest;

import com.byb.server.security.jwt.JWTConfigurer;
import com.byb.server.service.UtilService;
import com.byb.server.service.dto.Wc.NormalAccessTokenDTO;
import com.byb.server.service.dto.Wc.WCAppInfoDTO;
import com.byb.server.service.util.ImageBase64Utils;
import com.byb.server.web.rest.util.HeaderUtil;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.github.jhipster.web.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.beans.Encoder;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Optional;

/**
 *
 * REST controller for Utils.
 */
@RestController
@RequestMapping("/api")
public class Utils {

    private final Logger log = LoggerFactory.getLogger(Utils.class);


    //外部请求图片地址
    private final String url = "http://www.biyibibaoxian.com/file/";

    //图片存储位置 /home/cdn/byibserver
    private final String relativePath="/home/cdn/byibserver";

    private final String urlWeChat_1="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb2b467961e051c00&redirect_uri=";

    private final String urlWeChat_2="&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    private final UtilService utilService;

    public Utils(UtilService utilService) {
        this.utilService = utilService;
    }

    /**
     *  表单提交image 返回图片链接
     * @param file
     * @return imageUrl
     */
    @PostMapping("/up_ImageFile")
    @Timed
    public ResponseEntity SaveImg(@RequestBody String file,HttpServletResponse response) throws URISyntaxException {
        File f = new File(relativePath);
        String stirng_1 =StringUtils.substringBefore(file,";");
        //截取base64字符串 提取图片格式
        String[] file_format= stirng_1.split("/");
        //提取图片Base64 编码字符串
        String[]  fileBase64=file.split(",");
        if(!f.exists()) {
            f.mkdirs();
        }
        //图片格式
        String format=file_format[1];
        //图片名
        String imageName=Long.toString(System.currentTimeMillis());
        Boolean isSave= ImageBase64Utils.base64ToImageFile(fileBase64[1],relativePath+"/"+imageName+"."+format);
        if (isSave){
            String link=url+imageName+"."+format;
            ImageLink result =new ImageLink(link);
            response.addHeader("picture", "post success");
            return ResponseEntity.ok(new ImageLink(link));
        }else {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * Object to return as body in SaveImg.
     */
    static class ImageLink {

        private String imageLink;

        public ImageLink(String imageLink) {
            this.imageLink = imageLink;
        }

        @JsonProperty("image_link")
        public String getImageLink() {
            return imageLink;
        }

        public void setImageLink(String imageLink) {
            this.imageLink = imageLink;
        }
    }



    /**
     *  根据Url 返回微信重定向url
     * @param redirect_url
     * @return
     */
    @GetMapping("/getWeChatUrl")
    @Timed
    public ResponseEntity getWeChatUrl(@RequestParam(value = "redirect_url",required = false) String redirect_url) throws UnsupportedEncodingException {
        if(redirect_url!=null){
          String redirectUrl= URLEncoder.encode(redirect_url, "UTF-8");
            return  ResponseEntity.ok(new weChatUrl(urlWeChat_1+redirectUrl+urlWeChat_2 ));
        }else {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
    }
    /**
     * Object to return as body in getWeChatUrl.
     */
    static class weChatUrl {

        private String WeChat_redirect_url;

        public weChatUrl(String WeChat_redirect_url) {
            this.WeChat_redirect_url = WeChat_redirect_url;
        }

        @JsonProperty("WeChat_redirectUrl")
        public String getWeChat_redirect_url() {
            return WeChat_redirect_url;
        }

        public void setWeChat_redirect_url(String weChat_redirect_url) {
            WeChat_redirect_url = weChat_redirect_url;
        }
    }

    /**
     *  根据code 获取access_token
     * @param code
     * @return
     */
    @GetMapping("/postCode_weChat")
    @Timed
    public ResponseEntity postWeiXinCode(@RequestParam(value = "Code_WeChat")String code){
        String access_token_url_1="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb2b467961e051c00&secret=88eb9253342b43fe82f2c595da4f74cb&code=";
        String access_token_url_2="&grant_type=authorization_code";
        String respones = utilService.postWeiXinCode(access_token_url_1+code+access_token_url_2);
        return ResponseEntity.ok(respones);
    }

    @PostMapping("/up-file")
    @Timed
    public ResponseEntity<ImageLink> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return  ResponseEntity.ok(new ImageLink("文件爲空"));
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.debug("上传的文件名为 {}" , fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.debug("上传的后缀名为 {}" , suffixName);
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(relativePath+"/" + System.currentTimeMillis()+"-"+fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return  ResponseEntity.ok(new ImageLink(url+"/"+dest.getName()));
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @GetMapping("/get_wc_config")
    @Timed
    public ResponseEntity<WCAppInfoDTO> getWcConfig(@RequestParam("js_url") String url){
        log.debug("request weChat appConfig post wc_api url : {} ", url);
        WCAppInfoDTO wcAppInfoDTO =  utilService.getWc_config(url);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(wcAppInfoDTO));
    }






}
